﻿using System;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

namespace CCSManager
{
    /// <summary>
    /// Interaction logic for AppStatusRow.xaml
    /// </summary>
    public partial class AppStatusRow : UserControl
    {
        public AppStatus AppStatus;

        public AppStatusRow()
        {
            InitializeComponent();
        }

        public AppStatusRow(bool isLastRow)
        {
            InitializeComponent();
            SetIsLastRow(isLastRow);
        }

        public AppStatusRow(AppStatus appStatus)
        {
            InitializeComponent();
            _SetAppStatus(appStatus);
        }

        public AppStatusRow(AppStatus appStatus, bool isLastRow)
        {
            InitializeComponent();
            _SetAppStatus(appStatus);
            SetIsLastRow(isLastRow);
        }

        private void _SetAppStatus(AppStatus appStatus)
        {
            AppStatus = appStatus;
            AppStatus.LicensedUsers = appStatus.AppSalesData.Sum(d => d.LicensedUserCount);
            AppStatus.TotalInstalls = appStatus.AppSalesData.Sum(d => d.InstallCount);
            AppStatus.RecentInstalls = appStatus.AppSalesData.Where(d => d.Reported > DateTime.Now.AddMonths(-2)).Sum(d => d.InstallCount);
            AppStatus.RecentRev = appStatus.AppSalesData.Where(d => d.Reported > DateTime.Now.AddMonths(-2)).Sum(d => d.Revenue);
            AppStatus.TotalRev = appStatus.AppSalesData.Sum(d => d.Revenue);
            AppStatus.FeedBack = appStatus.AppSalesData.Sum(d => d.FeedbackCount);
            DataContext = AppStatus;
        }

        private void SetIsLastRow(bool isLastRow)
        {
            if (isLastRow)
            {
                AppNameBorder.CornerRadius = new CornerRadius(0, 0, 0, 6);
                TotalErrBorder.CornerRadius = new CornerRadius(0, 0, 6, 0);
            }
        }

        public event EventHandler AppNameClicked;

        private void AppNameText_Click(object sender, RoutedEventArgs e)
        {
            if (AppNameClicked != null)
            {
                AppNameClicked(this, new EventArgs());
            }
        }
    }

    [ValueConversion(typeof(object), typeof(string))]
    public class FormattingConverter : IValueConverter
    {
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var formatString = parameter as string;
            if (formatString != null)
            {
                return string.Format(culture, formatString, value);
            }
            return value.ToString();
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return null;
        }

        #endregion
    }
}